<template>
  <el-dialog v-model="open">
    <div style="display: flex">
      <div v-for="(item, index) in tagShows" :key="item?.id">
        <TagTest :text='item.describe' :total-color="item.color" :describe="item.remark"
                 fontSize="20px" :id="item.id" is-edit="1" @deleteTarget="deleteTag">
        </TagTest>
      </div>
    </div>
    <hr/>
    <ProTable
        ref="proTableRef"
        title="人物标签表"
        :indent="20"
        :columns="columns"
        :search-columns="searchColumns"
        :request-api="getTableList"
        row-key="id"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary"
                   v-auth="'novel.tag.create'"
                   :icon="CirclePlus"
                   @click="openAddEdit('新增人物标签表')"
        >
          新增
        </el-button>
        <el-button
            v-auth="'novel.tag.remove'"
            type="danger"
            :icon="Delete"
            plain
            :disabled="!scope.isSelected"
            @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <template #operation="{ row }">
        <el-button
            v-auth="'novel.tag.update'"
            type="primary"
            link
            :icon="EditPen"
            @click="openAddEdit('编辑人物标签表', row, false)"
        >
          编辑
        </el-button>
        <el-button
            v-auth="'novel.tag.remove'"
            type="primary"
            link
            :icon="Delete"
            @click="deleteInfo(row)"
        >
          删除
        </el-button>
      </template>
    </ProTable>
    <ChararterTagForm ref="chararterTagRef" />

    <template #footer>
      <el-button @click="open = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {h, onBeforeUnmount, reactive, ref, watch} from "vue";
import {CirclePlus, Delete, EditPen} from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import type {ColumnProps, ProTableInstance} from "@/components/ProTable/interface";
import type {ChararterTagQuery, ChararterTagRow, TagRelate} from "@/api/types/novel/chararterTag";
import tagTest from "@/views/novel/tag/components/Children/tagTest.vue";
import {useDictOptions} from "@/hooks/useDictOptions";
import {
  batchSaveRelative,
  createChararterTagApi,
  getChararterTagDetailApi,
  getChararterTagListApi,
  getDetailModeTagListApi,
  importChararterTagExcelApi,
  removeChararterTagApi,
  updateChararterTagApi
} from "@/api/modules/novel/chararterTag";
import ChararterTagForm from "@/views/novel/tag/components/test.vue";
import {useHandleData} from "@/hooks/useHandleData";
import ImportExcel from "@/components/ImportExcel/index.vue";
import {downloadTemplate} from "@/api/modules/system/common";
import onSelectColor from "@/views/novel/tag/components/Children/onSelectColor.vue";
import type {  SearchProps } from '@/components/ProTable/interface';
import TagTest from "@/views/novel/tag/components/Children/tagTest.vue";
import {ElMessage} from "element-plus";


let open = ref();
const proTableRef = ref<ProTableInstance>();
let tagShows = ref()
let test = reactive({
  test: '测试',
  test2: '测试2',
  totalColor: 'rgba(172, 97, 57,0.1)',
  describe: '这是一段提示',
  fontSize: '25px'
})

let props =defineProps({
  masterId: Number,
})

let openTagDialog = (id: any)=>{
  // if (id){
  //   getDetailModeTipsDetailApi( { id: id }).then( res=>{
  //     console.log('获得数据res',res)
  //     data.id = res?.data?.id
  //     data.imageUrl = res?.data?.pictureId
  //     Object.assign(data.orgin,res?.data)
  //     console.log('变更后的数据data',data)
  //
  //   })
  // }
  getTableList({})
  open.value =true;
}

let emit = defineEmits(['refreshTags'])
/**
 * 处理提交
 */
let handleSubmit = ()=>{
    console.log('showSasdfw',tagShows?.value)
    if (tagShows?.value){
      let updates =tagShows?.value.map((row: any) => {
        let test: TagRelate = {  // 直接定义为 TagRelate 类型
          ...row  // 使用 row 的数据赋值给 test
        };
        test.belongType='人物'
        test.busId = props.masterId
        test.tagId = row.id
        return test;
      });
      console.log('updatesupdatesupdates',updates);
      batchSaveRelative(updates).then((res) => {
        ElMessage.success(res)
        open.value = false;
        emit('refreshTags','')
      });
    }
}


const columns: ColumnProps<ChararterTagRow>[] = [
  { type: 'selection', width: 80 },
  { prop: 'describe',
    label: '标签文本',
    render: (params: any) => {
      return h(tagTest, {
        text: params.row.describe,
        totalColor : params.row.color,
        describe : params.row.remark,
        fontSize: '16px'
      })
    },},
  { prop: 'remark', label: '备注' },
  {
    prop: 'tagType',
    label: '标签类型',
    enum: useDictOptions('tagType'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  },
  { prop: 'operation', label: '操作', width: 250, fixed: 'right' }
]


// 搜索条件项
const searchColumns: SearchProps[] = [
  {
    prop: 'color',
    label: '颜色',
    el: 'input',
    render: (params: any) => {
      return h(onSelectColor, {
        id: 'tagColorOut',
        modelValue: params.modelValue,
        'onUpdate:modelValue': params['onUpdate:modelValue'],
        placeholder: '点击选择颜色'
      });
    },
  },
  // { prop: 'colorCode', label: '颜色网页码', el: 'input' },
  { prop: 'describe', label: '标签文本', el: 'input' },
  // { prop: 'tagType', label: '标签类型', el: 'select' },
  {
    prop: 'tagType',
    label: '标签类型',
    el: 'select',
    enum: useDictOptions('tagType'),
    fieldNames: {
      label: 'codeName',
      value: 'id',
      tagType: 'callbackShowStyle'
    }
  }
]

let deleteTag = (id :any) =>{
  console.log('iddfqwefrqwer',id)
  let results = tagShows?.value.filter((v: any) => v.id !== id)
  tagShows?.value.splice(0, tagShows?.value.length);
  tagShows?.value.splice(0, 0, ...results);
  proTableRef?.value?.defaultSelect(tagShows?.value);
}


// 获取table列表
const getTableList = (params: ChararterTagQuery) => {
  let newParams = formatParams(params);
  let data =getChararterTagListApi(newParams)
  getDetailTags(data)
  return data
};


const formatParams = (params: ChararterTagQuery) =>{
  let newParams = JSON.parse(JSON.stringify(params));
  if(newParams.createTime) {
    newParams.createTimeStart = newParams.createTime[0];
    newParams.createTimeEnd = newParams.createTime[1];
    delete newParams.createTime;
  }

  if(newParams.updateTime) {
    newParams.updateTimeStart = newParams.updateTime[0];
    newParams.updateTimeEnd = newParams.updateTime[1];
    delete newParams.updateTime;
  }

  return newParams;
}
// 打开 drawer(新增、查看、编辑)
const chararterTagRef = ref<InstanceType<typeof ChararterTagForm>>()
const openAddEdit = async(title: string, row: any = {}, isAdd = true) => {
  if (!isAdd) {
    const record = await getChararterTagDetailApi({ id: row?.id })
    row = record?.data
  }
  const params = {
    title,
    row: { ...row },
    api: isAdd ? createChararterTagApi : updateChararterTagApi,
    getTableList: proTableRef.value?.getTableList
  }
  chararterTagRef.value?.acceptParams(params)
}
// 删除信息
const deleteInfo = async (params: ChararterTagRow) => {
  await useHandleData(
      removeChararterTagApi,
      { ids: [params.id] },
      `删除【${params.id}】人物标签表`
  )
  proTableRef.value?.getTableList()
}
// 批量删除信息
const batchDelete = async (ids: (string | number)[]) => {
  await useHandleData(removeChararterTagApi, { ids }, '删除所选人物标签表')
  proTableRef.value?.clearSelection()
  proTableRef.value?.getTableList()
}
// 导入
const ImportExcelRef = ref<InstanceType<typeof ImportExcel>>()
const importData = () => {
  const params = {
    title: '人物标签表',
    templateName: '人物标签表',
    tempApi: downloadTemplate,
    importApi: importChararterTagExcelApi,
    getTableList: proTableRef.value?.getTableList
  }
  ImportExcelRef.value?.acceptParams(params)
}

let getDetailTags = (tagListP : any)=>{
  tagListP.then((tagListRes: any)=>{
    getDetailModeTagListApi({busId:props.masterId}).then(res=>{
      tagShows.value = res?.data?.rows;
      let needIds = tagShows.value.map((row: any) => { return row?.tagId });
      let selectObjs = tagListRes?.data?.rows.filter((row: any) => {
        return needIds.includes(row?.id);
      });
      proTableRef?.value?.defaultSelect(selectObjs);
    })
  })
}


//监控选择框
watch(() => proTableRef?.value?.selectedList,
    (newvalue : any) => {
        console.log('newvaluenewvaluenewvalue',newvalue)
        tagShows?.value?.splice(0, tagShows?.value.length);
        tagShows?.value?.splice(0, 0, ...newvalue);
    })

const areEqual = (a: any[], b: any[]) => {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false;
  }
  return true;
};

// onBeforeUnmount(()=>{
//   console.log('onBeforeUnmount卸载')
//   tagShows.value = []
//   proTableRef?.value?.defaultSelect([]);
// })

watch( open ,
    (newvalue : any) => {
        //为关闭时
        if (!newvalue){
          console.log('触发了关闭')
          tagShows.value = []
          proTableRef?.value?.defaultSelect([]);
        }
    })



defineExpose({openTagDialog})
</script>

<style scoped lang="scss">


.image-container {
  text-align: center;
  padding: 20px;
}

img {
  max-width: 100%;
  max-height: 300px;
  margin-top: 20px;
}
</style>